package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务类
 *
 * @Author katana
 * @Date 2025/5/21 17:16
 */
@Component
@Slf4j
public class OrderTask {
    
    @Autowired
    private OrderMapper orderMapper;
    
    /**
     * 处理支付超时订单
     * 每分钟检查一次是否存在支付超时订单（下单后超过15分钟仍未支付则判定为支付超时订单），如果存在则修改订单状态为“已取消”
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        //获取15分钟后的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        
        //查询状态为“待付款”且下单时间小于15分钟前的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        if (ordersList != null && ordersList.size() > 0){
            log.info("处理支付超时订单：{}", LocalDateTime.now());
            for (Orders orders : ordersList) {
                //更新订单状态为4
                Orders order = Orders.builder()
                        .id(orders.getId())
                        .status(Orders.CANCELLED)
                        .cancelReason("支付超时，取消订单")
                        .cancelTime(LocalDateTime.now())
                        .build();
                orderMapper.update(order);
            }
        }
    }
    
    /**
     * 处理“派送中”状态的订单
     * 每天凌晨1点检查一次是否存在“派送中”的订单，如果存在则修改订单状态为“已完成”
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", LocalDateTime.now());
        
        //获取一小时前的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        
        if(ordersList != null && ordersList.size() > 0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
